﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ToWaDBFirst.Models;

namespace ToWaDBFirst.Controllers
{
    /**
     * Controller to manage the creation, joining, leaving and inspecting of groups.
     **/
    [Authorize]
    public class GroupController : Controller
    {

        /**
         * Class objects to be used for database and service operations.
         **/
        ToWaService service = new ToWaService();
        ToWaDBFirstDBEntities2 db = new ToWaDBFirstDBEntities2();
        
        /**
         * Method for the index page of the groups. Returns a list of groups to the View.
         **/
        // GET: /Group/
        public ActionResult Index()
        {
            return View(service.GetGroups(User.Identity.Name));
        }

        /**
         * Method for the details page of the groups. Collects information from the database with the specified id
         * and returns it to the View.
         **/
        // GET: /Group/Details/
        public ActionResult Details(int id)
        {
            var group = db.groups.Single(g => g.id == id);
            return View(group);
        }

        /**
         * Method to join an existing group. Adds the userId to the groupId in the database.
         * Returns to the details View with updated information about the group.
         **/
        // GET: /Group/Join/
        public ActionResult Join(int id)
        {
            service.JoinGroup(id, User.Identity.Name);

            return RedirectToAction("Details", new { id = id });
        }

        /**
         * Method to leave an existing group with the specified id with the current logged in user.
         * Returnss to the details View with updated information about the group.
         **/
        // GET: /Group/
        public ActionResult Leave(int id)
        {
            service.LeaveGroup(id, User.Identity.Name);

            return RedirectToAction("Details", new { id = id });
        }

        /**
         * Get method of the HttpPost create method.
         **/
        // GET: /Group/Create
        public ActionResult Create()
        {
            return View();
        } 

        /**
         * Method to create a group with a unique name. Database will not allow multiple groups with the same name.
         * Returns to the Index View (/Home/Index).
         **/
        // POST: /Group/Create
        [HttpPost]
        public ActionResult Create(group group)
        {
            try
            {
                db.groups.Add(group);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
